package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.SportDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Sport;
import com.itheima.service.SportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service(interfaceClass = SportService.class)
@Transactional
public class SportServiceImpl implements SportService {
    @Autowired
    private SportDao sportDao;

    @Override
    public void add(ArrayList<Sport> list) {
        if (list != null && list.size() > 0) {
            for (Sport sport : list) {
                int count = sportDao.findCountByCode(sport.getCode());
                if (count > 0) {
                    sportDao.edit(sport);
                } else {
                    sportDao.add(sport);
                }
            }
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //分页助手插件
        PageHelper.startPage(currentPage, pageSize);
        Page<Sport> page = sportDao.selectByCondition(queryString);
        long total = page.getTotal();
        List<Sport> rows = page.getResult();
        return new PageResult(total, rows);
    }

    @Override
    public void save(Sport sport) {
        sportDao.add(sport);
    }

    @Override
    public void delete(Integer id) {
        sportDao.delete(id);
    }

    @Override
    public void edit(Sport sport) {
        sportDao.update(sport);
    }

    @Override
    public Sport findById(Integer id) {
        return sportDao.findById(id);
    }
}
